<template>
  <el-card class="chart-card">
    <template #header>
      <div style="display: flex; justify-content: space-between; align-items: center">
        <span>访问趋势</span>
        <el-space>
          <span style="color: #909399">分组方式:</span>
          <el-select 
            :model-value="groupBy"
            @update:model-value="handleGroupByChange"
            style="width: 120px"
          >
            <el-option label="按天" value="day" />
            <el-option label="按周" value="week" />
            <el-option label="按月" value="month" />
          </el-select>
        </el-space>
      </div>
    </template>
    
    <div v-if="!data || data.length === 0" style="padding: 50px; text-align: center">
      <el-empty description="暂无访问趋势数据" />
    </div>
    <div v-else ref="chartRef" style="width: 100%; height: 400px"></div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

interface Props {
  data?: any[]
  isLoading?: boolean
  groupBy?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  groupByChange: [value: string]
}>()

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 处理数据
const processedData = computed(() => {
  const dates: string[] = []
  const pvData: number[] = []
  const uvData: number[] = []
  
  if (!props.data || props.data.length === 0) {
    return { dates, pvData, uvData }
  }
  
  props.data.forEach(item => {
    const dateValue = item.date || item.week || item.month
    if (dateValue) {
      const date = dayjs(dateValue).format('MM-DD')
      dates.push(date)
      pvData.push(Number(item.pv) || 0)
      uvData.push(Number(item.uv) || 0)
    }
  })
  
  return { dates, pvData, uvData }
})

const handleGroupByChange = (value: string) => {
  emit('groupByChange', value)
}

const initChart = () => {
  if (!chartRef.value) {
    return
  }
  
  const hasData = processedData.value.dates && processedData.value.dates.length > 0
  if (!hasData) {
    return
  }
  
  
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  chartInstance = echarts.init(chartRef.value)
  
  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['总访问量', '独立访客'],
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: processedData.value.dates,
      name: '日期'
    },
    yAxis: {
      type: 'value',
      name: '访问量'
    },
    series: [
      {
        name: '总访问量',
        type: 'line',
        smooth: true,
        data: processedData.value.pvData,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      },
      {
        name: '独立访客',
        type: 'line',
        smooth: true,
        data: processedData.value.uvData,
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }
            ]
          }
        }
      }
    ],
    animation: true,
    animationDuration: 1000
  }
  
  chartInstance.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    // 延迟初始化，确保 DOM 已完全渲染
    setTimeout(() => {
      initChart()
    }, 100)
    window.addEventListener('resize', handleResize)
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

watch(() => props.data, () => {
  nextTick(() => {
    setTimeout(() => {
      initChart()
    }, 150)
  })
}, { deep: true, immediate: false })

watch(() => props.groupBy, () => {
  nextTick(() => {
    setTimeout(() => {
      initChart()
    }, 150)
  })
})

const handleResize = () => {
  chartInstance?.resize()
}
</script>

<style scoped lang="scss">
.chart-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
</style>

